use std::path::Path;
use tokio::process::Command;

pub struct SnapInstaller;

impl SnapInstaller {
    pub async fn install(&self, path: &str) -> Result<(), String> {
        let path = Path::new(path);
        if !path.exists() {
            return Err("文件不存在".into());
        }
        
        // 验证 Snap 包完整性
        if !self.verify_snap(path).await? {
            return Err("无效的 Snap 包".into());
        }
        
        // 执行安装
        let output = Command::new("sudo")
            .args(&["snap", "install", "--dangerous", path.to_str().unwrap()])
            .output()
            .await
            .map_err(|e| e.to_string())?;
        
        if output.status.success() {
            Ok(())
        } else {
            Err(String::from_utf8_lossy(&output.stderr).into())
        }
    }

    async fn verify_snap(&self, path: &Path) -> Result<bool, String> {
        let output = Command::new("unsquashfs")
            .args(&["-l", path.to_str().unwrap()])
            .output()
            .await
            .map_err(|e| e.to_string())?;
        
        Ok(output.status.success() && 
            String::from_utf8_lossy(&output.stdout).contains("snap"))
    }
}